<template>
	<view class="switch-container">
		<scroll-view scroll-y class="switch-list">
			<view class="list-wrapper">
				<view class="switch-item" v-for="(item, index) in switchList" :key="index">
					<view class="switch-info">
						<view class="switch-title">{{item.name_value}}</view>
						<view class="switch-desc">{{item.description}}</view>
					</view>
					<switch 
						:checked="item.value" 
						:disabled="item.disable"
						@change="handleSwitchChange($event, item)"
						color="#07c160"
					/>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import request from '@/utils/request'

	export default {
		data() {
			return {
			switchList: []
			}
	},
	onShow() {
		this.getSwitchList()
		},
		methods: {
		// 获取开关列表
		async getSwitchList() {
			try {
				const res = await request({
					url: '/wechat/messageSwitch/lists'
				})
				
				if (res.code === 0 && res.data) {
					this.switchList = res.data
				}
			} catch (err) {
				console.error('获取开关列表失败', err)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			}
		},
		
		// 处理开关切换
		async handleSwitchChange(e, item) {
			if (item.disable) return
			
			try {
				const res = await request({
					url: '/wechat/messageSwitch/change',
					data: {
						name: item.name,
						value: e.detail.value
					}
				})
				
				if (res.code === 0 && res.data) {
					// 使用返回的数据更新列表
					this.switchList = res.data
					uni.showToast({
						title: '更新成功',
						icon: 'success'
					})
				} else {
					throw new Error(res.message || '更新失败')
				}
			} catch (err) {
				console.error('更新开关状态失败', err)
				uni.showToast({
					title: err.message || '更新失败',
					icon: 'none'
				})
				// 刷新列表以恢复原始状态
				this.getSwitchList()
			}
		}
		}
	}
</script>

<style>
.switch-container {
	min-height: 100vh;
	background-color: #f8f9fc;
	padding: 30rpx;
}

.switch-list {
	height: 100vh;
}

.list-wrapper {
	padding: 0;
}

.switch-item {
	background-color: #ffffff;
	margin-bottom: 20rpx;
	border-radius: 24rpx;
	padding: 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.switch-info {
	flex: 1;
	margin-right: 20rpx;
}

.switch-title {
	font-size: 30rpx;
	color: #333333;
	font-weight: 500;
	margin-bottom: 12rpx;
}

.switch-desc {
	font-size: 26rpx;
	color: #666666;
	line-height: 1.5;
}
</style>
